package com.iot08.admin.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @version 1.0
 * @Description: 阿里云oss上传
 * @author: Rock
 * @time: 2020/10/22 17:36
 */
@Slf4j
@Component
public class AliyunOSSUtil {

    @Value("${aliyun.oss.url}")
    private String url;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    public static String DOMAIN;

    @Value("${aliyun.oss.domain}")
    public void setDomain(String domain){
        DOMAIN = domain;
    }



    /**
     * 上传图片
     *
     * @param path
     * @param file
     * @time: 2020/10/22 17:59
     * @author: Rock
     * @version 1.0
     */
    public void upload(String path, MultipartFile file) throws IOException {
        // 取得上传文件
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getInputStream().available());
        // 可以在metadata中标记文件类型
        objectMetadata.setContentType("image/jpeg");
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(url, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, path, file.getInputStream(), objectMetadata);
        // 关闭client
        ossClient.shutdown();
        log.info("上传成功： " + path);
    }


}